#include "stdafx.h"
#include "cv.h"
#include "highgui.h"

CvSeq* contours = 0;
CvSeq* dps = 0;
//int CV_DOMINANT_IPAN=0;

int main( int argc, char** argv )
{
    int i, idx;
    CvPoint p;
    CvMemStorage* storage_ct = cvCreateMemStorage(0);
    CvMemStorage* storage_dp = cvCreateMemStorage(0);
    IplImage* img = cvLoadImage("contour.bmp", CV_LOAD_IMAGE_GRAYSCALE);

    cvNamedWindow( "image" , CV_WINDOW_AUTOSIZE);
    cvShowImage( "image", img );

    cvFindContours( img, storage_ct, &contours, sizeof(CvContour),
        CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE ,cvPoint(0,0));

    dps = cvFindDominantPoints( contours, storage_dp, CV_DOMINANT_IPAN, 7, 20, 9, 150 );

    contours = cvApproxPoly( contours, sizeof(CvContour), storage_ct, CV_POLY_APPROX_DP, 3, 1 );

    printf("found %d DPs and %d Contours \n", dps->total, contours->total );

    for ( i = 0; i < dps->total; i++)
    {
        idx = *(int *) cvGetSeqElem(dps, i);
        p = *(CvPoint *) cvGetSeqElem(contours, idx);
        cvDrawCircle( img, p , 1, cvScalarAll(255) ,1, 8, 0);
        printf("%d %d %d\n", idx, p.x, p.y);
    }

    cvDrawContours(img, contours, cvScalarAll(100), cvScalarAll(200), 100 ,1, 8, cvPoint(0,0));


    cvNamedWindow( "contours" , CV_WINDOW_AUTOSIZE);
    cvShowImage( "contours", img );

    cvWaitKey(0);
    cvReleaseMemStorage( &storage_ct );
    cvReleaseMemStorage( &storage_dp );
    cvReleaseImage( &img );

    return 0;
}
